package com.lzy.okgo.harmony.ui.itemprovider;

import com.lzy.okgo.harmony.ResourceTable;
import com.lzy.okgo.harmony.model.HomeArticleModel;
import com.lzy.okgo.utils.TextUtils;
import ohos.agp.components.*;
import ohos.app.Context;
import org.apache.commons.lang.StringEscapeUtils;

import java.util.List;

/**
 * 首页文章列表适配器
 */
public class HomeArticleItemProvider extends BaseItemProvider {
    private final List<HomeArticleModel> mListData;

    public HomeArticleItemProvider(List<HomeArticleModel> list) {
        this.mListData = list;
    }

    @Override
    public int getCount() {
        return mListData.size();
    }

    @Override
    public Object getItem(int position) {
        return mListData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer container) {
        Context context = container.getContext();
        HomeArticleModel itemModel = mListData.get(position);
        ViewHolder viewHolder;
        if (convertComponent == null) {
            convertComponent = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_item_home_article, container, false);
            viewHolder = new ViewHolder(convertComponent);
            convertComponent.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertComponent.getTag();
        }
        if (!TextUtils.isEmpty(itemModel.getTitle())) {
            //json里面有一些特殊符号，特殊符号会被gson转义，
            //StringEscapeUtils可以对转义的字符串进行反转义
            //调用StringEscapeUtils的unescapeHtml方法，如果字符串中没有转义字符，
            //unescapeHtml方法会直接返回原字符串，否则会对字符串进行反转义。
            String title = StringEscapeUtils.unescapeHtml(itemModel.getTitle());
            //标题
            viewHolder.vTitle.setText(title);
        } else {
            viewHolder.vTitle.setText("");
        }
        String name;
        if (!TextUtils.isEmpty(itemModel.getAuthor())) {
            name = itemModel.getAuthor();
        } else {
            name = itemModel.getShareUser();
        }
        //姓名
        viewHolder.vUserName.setText(name);
        //日期
        viewHolder.vDate.setText(itemModel.getNiceShareDate());
        return convertComponent;
    }

    private static class ViewHolder {
        private final Text vTitle;
        private final Text vUserName;
        private final Text vDate;

        public ViewHolder(Component itemView) {
            vTitle = (Text) itemView.findComponentById(ResourceTable.Id_title);
            vUserName = (Text) itemView.findComponentById(ResourceTable.Id_user_name);
            vDate = (Text) itemView.findComponentById(ResourceTable.Id_date);
        }
    }
}